package zhangmengna.dao;

import org.hibernate.Session;
import zhangmengna.entity.Page;
import zhangmengna.entity.ZMNBJEntity;
import zhangmengna.entity.ZMNEntity;
import org.hibernate.Query;
import org.hibernate.transform.Transformers;
import org.springframework.orm.hibernate4.support.HibernateDaoSupport;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class ZMNDao extends HibernateDaoSupport {
    public List<ZMNEntity> queryPage(Page page, String name) {
        String sql = "select a.name,a.id,a.url,b.bname,a.age,a.sex from j05zhangmengna a,j05zmnclazz b where a.bid=b.bid and  name like ? order by a.id desc limit ?,? ";
        Query query=getSessionFactory().openSession().createSQLQuery(sql);
        query.setParameter(0,  "%" + name + "%");
        query.setParameter(1,page.getBeginIndex());
        query.setParameter(2,page.getEveryPage());
        //将查询结果转成Map对象的集合
        // query.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP);
        query.setResultTransformer(Transformers.aliasToBean(ZMNEntity.class));
        List<ZMNEntity> list=  query.list();

        return  list;
    }

    //  添加
    public void add(ZMNEntity zmnEntity) {
        Session session=getSessionFactory().openSession();
        session.saveOrUpdate(zmnEntity);
        session.flush();
    }

    public int queryCount(String name) {
        String sql="select * from j05zhangmengna where name like ?";
        Query query=getSessionFactory().openSession().createSQLQuery(sql);
        query.setParameter(0,  "%" + name + "%");
        List<ZMNEntity> list=  query.list();
        return list.size();
    }

    public ZMNEntity edit(ZMNEntity zmnEntity) {
        return (ZMNEntity) getSessionFactory().openSession().get(ZMNEntity.class,zmnEntity.getId());
    }

    public void del(ZMNEntity zmnEntity) {
        Session session=getSessionFactory().openSession();
        session.delete(zmnEntity);
        System.out.println("123");
        session.flush();
    }
//班级
    public List<ZMNBJEntity> clazz() {
        String sql = "select * from j05zmnclazz ";
        Query query=getSessionFactory().openSession().createSQLQuery(sql);
        query.setResultTransformer(Transformers.aliasToBean(ZMNBJEntity.class));
        List<ZMNBJEntity> list=  query.list();
        return  list;
    }
}
